<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Raintee全流程APP版本管理系统</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css"
      rel="stylesheet"
    />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
    />
    <style>
      :root {
        --primary-color: #4361ee;
        --secondary-color: #3f37c9;
        --accent-color: #4cc9f0;
        --dark-color: #1a1a2e;
        --light-color: #f8f9fa;
        --success-color: #4caf50;
        --warning-color: #ff9800;
        --danger-color: #f44336;
        --card-bg: rgba(255, 255, 255, 0.9);
        --glass-effect: rgba(255, 255, 255, 0.15);
      }

      body {
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        color: #fff;
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        min-height: 100vh;
      }

      .container {
        max-width: 1200px;
      }

      h1,
      h2,
      h3,
      h4,
      h5,
      h6 {
        font-weight: 600;
      }

      .version-card {
        transition: all 0.3s ease;
        background: var(--card-bg);
        border: none;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        transform: translateY(0);
      }

      .version-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.3);
      }

      .form-section {
        background: var(--glass-effect);
        border-radius: 16px;
        padding: 2rem;
        margin-bottom: 2rem;
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
      }

      .card {
        background: var(--glass-effect);
        border: none;
        border-radius: 12px;
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
        color: white;
      }

      .list-group-item {
        background-color: rgba(255, 255, 255, 0.1);
        color: white;
        border-color: rgba(255, 255, 255, 0.1);
      }

      .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        transition: all 0.3s;
      }

      .btn-primary:hover {
        background-color: var(--secondary-color);
        border-color: var(--secondary-color);
        transform: translateY(-2px);
      }

      .btn-outline-primary {
        color: var(--accent-color);
        border-color: var(--accent-color);
      }

      .btn-outline-primary:hover {
        background-color: var(--accent-color);
        color: white;
      }

      .form-control,
      .form-select {
        background-color: rgba(255, 255, 255, 0.1);
        border-color: rgba(255, 255, 255, 0.2);
        color: white;
      }

      .form-control:focus,
      .form-select:focus {
        background-color: rgba(255, 255, 255, 0.2);
        border-color: var(--accent-color);
        color: white;
        box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
      }

      .form-text {
        color: rgba(255, 255, 255, 0.6) !important;
      }

      .badge {
        font-weight: 500;
        padding: 0.4em 0.8em;
      }

      .bg-primary {
        background-color: var(--primary-color) !important;
      }

      .bg-secondary {
        background-color: var(--secondary-color) !important;
      }

      .bg-success {
        background-color: var(--success-color) !important;
      }

      .bg-warning {
        background-color: var(--warning-color) !important;
      }

      .bg-danger {
        background-color: var(--danger-color) !important;
      }

      /* 高级开关样式 */
      .form-switch .form-check-input {
        width: 3em;
        height: 1.5em;
        background-color: rgba(255, 255, 255, 0.3);
        border: none;
      }

      .form-switch .form-check-input:checked {
        background-color: var(--primary-color);
      }

      .form-switch .form-check-input:focus {
        box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
      }

      /* 模态框样式 */
      .modal-content {
        background: var(--dark-color);
        color: white;
        border: 1px solid rgba(255, 255, 255, 0.1);
      }

      .modal-header {
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      }

      .modal-footer {
        border-top: 1px solid rgba(255, 255, 255, 0.1);
      }

      .btn-close {
        filter: invert(1);
      }

      /* 动画效果 */
      .animate-fade-in {
        animation: fadeIn 0.6s ease-in-out;
      }

      @keyframes fadeIn {
        from {
          opacity: 0;
          transform: translateY(20px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      /* 响应式调整 */
      @media (max-width: 768px) {
        .form-section {
          padding: 1.5rem;
        }

        .version-card {
          margin-bottom: 1rem;
        }
      }

      /* 自定义滚动条 */
      ::-webkit-scrollbar {
        width: 8px;
      }

      ::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.05);
      }

      ::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
      }

      /* 粒子背景效果 */
      #particles-js {
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: -1;
      }

      /* 霓虹文字效果 */
      .neon-text {
        text-shadow: 0 0 5px var(--accent-color), 0 0 10px var(--accent-color),
          0 0 15px var(--accent-color);
      }

      /* 3D按钮效果 */
      .btn-3d {
        position: relative;
        transition: all 0.3s;
        transform-style: preserve-3d;
        perspective: 1000px;
      }

      .btn-3d:hover {
        transform: translateY(-3px) rotateX(10deg);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
      }

      .btn-3d:active {
        transform: translateY(1px);
      }
      /* 新增下拉框文字可见性优化 */
      .form-select {
        background-color: rgba(255, 255, 255, 0.1) !important;
        border-color: rgba(255, 255, 255, 0.3) !important;
        color: white !important;
      }

      .form-select:focus {
        background-color: rgba(255, 255, 255, 0.2) !important;
        color: white !important;
      }

      .form-select option {
        background-color: #2a2a3a;
        color: white;
      }

      /* 增强下拉箭头可见性 */
      .form-select {
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='white' fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
      }
    </style>
  </head>
  <body>
    <!-- 粒子背景 -->
    <div id="particles-js"></div>

    <div class="container py-4 animate__animated animate__fadeIn">
      <h1 class="text-center mb-4 neon-text">全流程APP版本管理系统</h1>

      <div class="row">
        <div class="col-lg-8">
          <div class="form-section animate-fade-in">
            <h2><i class="bi bi-cloud-arrow-up me-2"></i>发布新版本</h2>
            <form id="versionForm">
              <div class="row mb-3">
                <div class="col-md-4 mb-3">
                  <label for="versionType" class="form-label">版本类型</label>
                  <select class="form-select" id="versionType" required>
                    <option value="">选择类型</option>
                    <option value="stable">稳定版</option>
                    <option value="snapshot">快照版</option>
                    <option value="beta">测试版</option>
                  </select>
                </div>
                <div class="col-md-2 mb-3">
                  <label for="majorVersion" class="form-label">大版本号</label>
                  <input
                    type="number"
                    class="form-control"
                    id="majorVersion"
                    min="1"
                    required
                  />
                </div>
                <div class="col-md-2 mb-3">
                  <label for="minorVersion" class="form-label">小版本号</label>
                  <input
                    type="number"
                    class="form-control"
                    id="minorVersion"
                    min="0"
                    required
                  />
                </div>
                <div class="col-md-2 mb-3">
                  <label for="patchVersion" class="form-label"
                    >补丁版本号</label
                  >
                  <input
                    type="number"
                    class="form-control"
                    id="patchVersion"
                    min="0"
                    required
                  />
                </div>
              </div>

              <div class="mb-4">
                <label for="forceUpdateRange" class="form-label"
                  >强制更新范围 (可选)</label
                >
                <input
                  type="text"
                  class="form-control"
                  id="forceUpdateRange"
                  placeholder="例如: 1.2-1.6"
                />
                <div class="form-text">指定哪些版本需要强制更新到此版本</div>
              </div>

              <div class="mb-4">
                <label for="updateInfo" class="form-label">更新内容</label>
                <textarea
                  class="form-control"
                  id="updateInfo"
                  rows="3"
                  required
                ></textarea>
              </div>

              <div class="mb-4">
                <label for="apkFile" class="form-label">APK文件</label>
                <input
                  type="file"
                  class="form-control"
                  id="apkFile"
                  accept=".apk"
                  required
                />
                <div class="form-text">只接受.apk后缀的文件</div>
              </div>

              <button type="submit" class="btn btn-primary btn-3d w-100 py-3">
                <i class="bi bi-send me-2"></i>发布版本
              </button>
            </form>
          </div>
        </div>

        <div class="col-lg-4">
          <div class="card mb-4 animate-fade-in" style="animation-delay: 0.2s">
            <div class="card-body">
              <h5 class="card-title">
                <i class="bi bi-info-circle me-2"></i>系统信息
              </h5>
              <ul class="list-group list-group-flush mt-3">
                <li
                  class="list-group-item d-flex justify-content-between align-items-center"
                >
                  配置服务地址
                  <span class="badge bg-primary rounded-pill"
                    >{{protocol}}{{ip}}:{{configPort}}</span
                  >
                </li>
                <li
                  class="list-group-item d-flex justify-content-between align-items-center"
                >
                  APK名称模板
                  <span class="badge bg-secondary rounded-pill"
                    >{{apkName}}-{{apkVersionType}}-x.y.z.apk</span
                  >
                </li>
              </ul>
            </div>
          </div>

          <div class="card animate-fade-in" style="animation-delay: 0.4s">
            <div class="card-body">
              <h5 class="card-title">
                <i class="bi bi-download me-2"></i>最新版本
              </h5>
              <div id="latestVersion" class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                  <span class="visually-hidden">Loading...</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <h2 class="mt-5 mb-4"><i class="bi bi-list-ul me-2"></i>版本历史</h2>
      <div id="versionList" class="row">
        <div class="col-12 text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">确认删除</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            确定要删除这个版本吗？此操作无法撤销，并且会从服务器上删除APK文件。
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-danger" id="confirmDelete">
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
    <script>
      // 全局变量
      let currentDeleteId = null;
      const baseApiUrl = "./api"; // 改为相对路径

      // DOM加载完成后执行
      document.addEventListener("DOMContentLoaded", function () {
        // 加载版本列表
        loadVersions();

        // 加载最新版本
        loadLatestVersion();

        // 表单提交处理
        document
          .getElementById("versionForm")
          .addEventListener("submit", function (e) {
            e.preventDefault();
            submitVersion();
          });

        // 删除确认按钮
        document
          .getElementById("confirmDelete")
          .addEventListener("click", function () {
            if (currentDeleteId) {
              deleteVersion(currentDeleteId);
            }
          });
      });

      // 加载版本列表
      function loadVersions() {
        fetch(`${baseApiUrl}/versions`)
          .then((response) => response.json())
          .then((versions) => {
            const container = document.getElementById("versionList");
            container.innerHTML = "";

            if (versions.length === 0) {
              container.innerHTML = `
          <div class="col-12">
            <div class="alert alert-info">暂无版本记录</div>
          </div>
        `;
              return;
            }

            versions.forEach((version, index) => {
              const versionCard = document.createElement("div");
              versionCard.className = "col-md-6 mb-4 animate-fade-in";
              versionCard.style.animationDelay = `${index * 0.1}s`;
              versionCard.innerHTML = `
          <div class="card version-card h-100">
            <div class="card-body">
              <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="card-title mb-0">
                  ${getVersionTypeBadge(version.version_type)} 
                  <span class="ms-2">v${version.major_version}.${
                version.minor_version
              }.${version.patch_version}</span>
                </h5>
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" role="switch" 
                    id="switch-${version.id}" ${
                version.is_active ? "checked" : ""
              }
                    onchange="toggleVersionStatus(${version.id}, this.checked)">
                </div>
              </div>
              <p class="card-text text-muted"><small>发布时间: ${
                version.publish_time
              }</small></p>
              ${
                version.force_update_range
                  ? `
                <p class="card-text mb-3">
                  <span class="badge bg-warning text-dark">强制更新: ${version.force_update_range}</span>
                </p>
              `
                  : ""
              }
              <div class="card-text mb-3 p-3 bg-dark rounded">${
                version.update_info
              }</div>
              <div class="d-flex justify-content-between align-items-center">
                <a href="${
                  version.apk_url
                }" class="btn btn-sm btn-outline-primary btn-3d">
                  <i class="bi bi-download me-1"></i>下载APK
                </a>
                <button class="btn btn-sm btn-outline-danger btn-3d" 
                  onclick="showDeleteConfirm(${version.id})">
                  <i class="bi bi-trash me-1"></i>删除
                </button>
              </div>
            </div>
          </div>
        `;
              container.appendChild(versionCard);
            });
          })
          .catch((error) => {
            console.error("Error loading versions:", error);
            document.getElementById("versionList").innerHTML = `
        <div class="col-12">
          <div class="alert alert-danger">加载版本列表失败: ${error.message}</div>
        </div>
      `;
          });
      }

      // 加载最新版本
      function loadLatestVersion() {
        fetch(`${baseApiUrl}/versions/latest`)
          .then((response) => response.json())
          .then((version) => {
            const container = document.getElementById("latestVersion");

            if (!version.id) {
              container.innerHTML =
                '<div class="alert alert-info">暂无可用版本</div>';
              return;
            }

            container.innerHTML = `
        <div class="p-3 bg-dark rounded mb-3">
          <h4 class="text-primary">${getVersionTypeText(
            version.version_type
          )} v${version.major_version}.${version.minor_version}.${
              version.patch_version
            }</h4>
          <p class="text-muted">${version.publish_time}</p>
        </div>
        <a href="./${
          version.apk_url
        }" class="btn btn-primary btn-3d w-100 py-2">
          <i class="bi bi-download me-2"></i>立即下载
        </a>
      `;
          })
          .catch((error) => {
            console.error("Error loading latest version:", error);
            document.getElementById("latestVersion").innerHTML = `
        <div class="alert alert-danger">加载最新版本失败</div>
      `;
          });
      }

      // 提交新版本
      function submitVersion() {
        const form = document.getElementById("versionForm");
        const formData = new FormData();

        // 收集表单数据
        formData.append(
          "version_type",
          document.getElementById("versionType").value
        );
        formData.append(
          "major_version",
          document.getElementById("majorVersion").value
        );
        formData.append(
          "minor_version",
          document.getElementById("minorVersion").value
        );
        formData.append(
          "patch_version",
          document.getElementById("patchVersion").value
        );
        formData.append(
          "force_update_range",
          document.getElementById("forceUpdateRange").value
        );
        formData.append(
          "update_info",
          document.getElementById("updateInfo").value
        );
        formData.append("apk", document.getElementById("apkFile").files[0]);

        // 显示加载状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalBtnText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML =
          '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>发布中...';

        // 发送请求
        fetch(`${baseApiUrl}/versions`, {
          method: "POST",
          body: formData,
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.error) {
              throw new Error(data.error);
            }
            // 显示成功通知
            showAlert("版本发布成功!", "success");
            form.reset();
            loadVersions();
            loadLatestVersion();
          })
          .catch((error) => {
            console.error("Error submitting version:", error);
            showAlert(`发布失败: ${error.message}`, "danger");
          })
          .finally(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalBtnText;
          });
      }

      // 切换版本状态
      function toggleVersionStatus(id, isActive) {
        fetch(`${baseApiUrl}/versions/${id}/status`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ is_active: isActive }),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.error) {
              throw new Error(data.error);
            }
            loadLatestVersion();
          })
          .catch((error) => {
            console.error("Error toggling version status:", error);
            showAlert(`状态更新失败: ${error.message}`, "danger");
            loadVersions(); // 重新加载以恢复原始状态
          });
      }

      // 显示删除确认对话框
      function showDeleteConfirm(id) {
        currentDeleteId = id;
        const deleteModal = new bootstrap.Modal(
          document.getElementById("deleteModal")
        );
        deleteModal.show();
      }

      // 删除版本
      function deleteVersion(id) {
        fetch(`${baseApiUrl}/versions/${id}`, {
          method: "DELETE",
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.error) {
              throw new Error(data.error);
            }
            // 关闭模态框
            const deleteModal = bootstrap.Modal.getInstance(
              document.getElementById("deleteModal")
            );
            deleteModal.hide();

            // 显示成功通知
            showAlert("版本删除成功!", "success");

            // 重新加载列表
            loadVersions();
            loadLatestVersion();
          })
          .catch((error) => {
            console.error("Error deleting version:", error);
            showAlert(`删除失败: ${error.message}`, "danger");
          });
      }

      // 辅助函数 - 获取版本类型徽章
      function getVersionTypeBadge(type) {
        const badges = {
          stable: '<span class="badge bg-success rounded-pill">稳定版</span>',
          snapshot: '<span class="badge bg-primary rounded-pill">快照版</span>',
          beta: '<span class="badge bg-warning text-dark rounded-pill">测试版</span>',
        };
        return badges[type] || "";
      }

      // 辅助函数 - 获取版本类型文本
      function getVersionTypeText(type) {
        const texts = {
          stable: "稳定版",
          snapshot: "快照版",
          beta: "测试版",
        };
        return texts[type] || type;
      }

      // 显示漂亮的提示通知
      function showAlert(message, type) {
        const alert = document.createElement("div");
        alert.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
        alert.style.zIndex = "9999";
        alert.style.minWidth = "300px";
        alert.innerHTML = `
      ${message}
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;

        document.body.appendChild(alert);

        // 5秒后自动消失
        setTimeout(() => {
          alert.classList.remove("show");
          setTimeout(() => alert.remove(), 150);
        }, 5000);
      }

      // 在您的现有脚本中添加以下代码
      document.addEventListener("DOMContentLoaded", function () {
        // 防止滚动恢复
        if ("scrollRestoration" in history) {
          history.scrollRestoration = "manual";
        }

        // 确保页面加载时在顶部
        window.scrollTo(0, 0);

        // 粒子动画可能导致的布局变化
        const particles = document.getElementById("particles-js");
        if (particles) {
          particles.style.position = "fixed";
          particles.style.zIndex = "-1";
        }
      });
    </script>
  </body>
</html>
